package com.xhwl.centiotdata.suppliersystem.huawei;

import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.pojo.constant.HuaWeiIoTDAConstant;
import com.xhwl.centiotdata.pojo.dto.huawei.PedestrianAuthHuaWeiIoTDTO;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.centiotdata.utils.Base64Utils;
import com.xhwl.centiotdata.utils.RedisUtils;
import com.xhwl.common.dto.cent.pedes.AuthDTO;
import com.xhwl.common.dto.cent.pedes.UserDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author： lianghz
 * @Description：
 * @Date 2021/09/03/ 09:44
 */
@Service
public class PedestrianHuaWeiIoTDAHandler {
    private static final Logger log = LoggerFactory.getLogger(PedestrianHuaWeiIoTDAHandler.class);
    private static final String ITEM_ID_KEY = "cent-pedestrian:auth-iot:%1$s_%2$s";

    @Autowired
    private GeneralHuaWeiIoTDAHandler generalHuaWeiIoTDAHandler;
    @Autowired
    private RedisUtils redisUtils;

    /**
     * 保存人员信息
     *
     * @param userDTO
     * @return
     */
    public String userSave(PedestrianIntegrationConfigDTO configDTO, UserDTO userDTO) {
        if(StringUtils.isEmpty(userDTO.getPhone())){
            userDTO.setPhone(this.getPhoneById(userDTO.getUserId()));
        }
        Map<String,Object> userParam = new HashMap<>();
        userParam.put("personName",userDTO.getName());
        userParam.put("mobile",userDTO.getPhone());
        Map<String,Object> param = new HashMap<>();
        param.put("CMD_ADD",userParam);
        JSONObject resultObject = generalHuaWeiIoTDAHandler.command(configDTO.getAk(), configDTO.getSk(), configDTO.getRegion(), configDTO.getUserDeviceId(), HuaWeiIoTDAConstant.SERVICE_USER, HuaWeiIoTDAConstant.COMMAND_USER_SAVE, param);
        return resultObject.getJSONObject("paras").getJSONObject("CommandRsBody").getJSONObject("data").getString("personId");
    }

    private String getPhoneById(String userId){
        if(StringUtils.isEmpty(userId)){
            return "13252995090";
        }
        if(userId.length() > 8){
            return "13252995098";
        }
        int cover = 8-userId.length();
        StringBuffer stringBuffer = new StringBuffer("130");
        for (int i = 0; i < cover; i++) {
            stringBuffer.append("0");
        }
        stringBuffer.append(userId);
        return stringBuffer.toString();
    }

    /**
     * 删除人员信息
     * todo 第三方人员信息暂且不删除
     *
     * @param userOpenId
     * @return
     */
    public String userDelete(PedestrianIntegrationConfigDTO configDTO, String userOpenId) {
        Map<String, Object> parasMap = new HashMap<>(1);
        parasMap.put("personId", userOpenId);
        Map<String,Object> param = new HashMap<>();
        param.put("CMD_DELETE",parasMap);
        JSONObject resultObject = generalHuaWeiIoTDAHandler.command(configDTO.getAk(), configDTO.getSk(), configDTO.getRegion(), configDTO.getUserDeviceId(), HuaWeiIoTDAConstant.SERVICE_USER, HuaWeiIoTDAConstant.COMMAND_USER_DELETE, param);
        return null;
    }

    /**
     * 保存授权信息
     *
     * @param authDTO
     * @return
     */
    public String pedestrianAuthSave(PedestrianIntegrationConfigDTO configDTO, AuthDTO authDTO) {
        Integer credentialType = null;
        if(!CollectionUtils.isEmpty(authDTO.getCardNumberList())||!StringUtils.isEmpty(authDTO.getCardNumber())){
            credentialType = 1;
        }
        String faceBase = null;
        if(!StringUtils.isEmpty(authDTO.getFaceUrl())){
            credentialType = 170;
            faceBase = Base64Utils.imageUrlToBase64(authDTO.getFaceUrl());
        }
        String itemId = UUID.randomUUID().toString();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String serviceStartDate = simpleDateFormat.format(authDTO.getStartTime());
        String serviceEndDate = simpleDateFormat.format(authDTO.getEndTime());
        List<String> deviceOpenIdList = authDTO.getDeviceOpenIdList();
        List<PedestrianAuthHuaWeiIoTDTO.IotDevice> deviceList = deviceOpenIdList.stream()
                .map(deviceOpenId -> PedestrianAuthHuaWeiIoTDTO.IotDevice.builder().deviceGuid(deviceOpenId).isDeleted(0).build())
                .collect(Collectors.toList());
        String cardNumber = authDTO.getCardNumber();//人脸卡号不能与门禁卡共用一张卡号
        if(credentialType == 170){
            cardNumber = "FF"+cardNumber.substring(2);
        }
        PedestrianAuthHuaWeiIoTDTO authHuaWeiIoTDTO = PedestrianAuthHuaWeiIoTDTO.builder()
                .cardServices(Collections.singletonList(PedestrianAuthHuaWeiIoTDTO.CardService.builder()
                        .deviceList(deviceList)
                        .itemId(itemId)
                        .credentialType(credentialType)
                        .credentialNo(cardNumber)
                        .personId(authDTO.getUserOpenId())
                        .serviceStartDate(serviceStartDate)
                        .serviceEndDate(serviceEndDate)
                        .cardKey("1234")
                        .templateData(faceBase)
                        .isDeleted(0)
                        .startTime1("00:00")
                        .endTime1("23:59")
                        .build()))
                .build();
        Map<String,Object> param = new HashMap<>();
        param.put("value",authHuaWeiIoTDTO);
        //	"response": {
        //		"paras": {
        //			"CommandMsg": "执行成功",
        //			"CommandResult": true,
        //			"CommandRsBody": null
        //		},
        //		"result_code": 1,
        //		"response_name": "getKey"
        //	}
        JSONObject resultObject = generalHuaWeiIoTDAHandler.command(configDTO.getAk(), configDTO.getSk(), configDTO.getRegion(), configDTO.getUserDeviceId(), HuaWeiIoTDAConstant.SERVICE_AUTHORIZATION, HuaWeiIoTDAConstant.COMMAND_AUTH, param);
        redisUtils.set(String.format(ITEM_ID_KEY, credentialType, authDTO.getUserOpenId()),itemId);
        return null;
    }


    /**
     * 更新授权信息
     *
     * @param authDTO
     * @return
     */
    public String pedestrianAuthUpdate(PedestrianIntegrationConfigDTO configDTO, AuthDTO authDTO) {
        Integer credentialType = null;
        String faceBase = null;
        if(!CollectionUtils.isEmpty(authDTO.getCardNumberList())||!StringUtils.isEmpty(authDTO.getCardNumber())){
            credentialType = 1;
        }
        if(!StringUtils.isEmpty(authDTO.getFaceUrl())){
            credentialType = 170;
            faceBase = Base64Utils.imageUrlToBase64(authDTO.getFaceUrl());
        }
        if(credentialType == null){
            return null;
        }
        String itemId = (String) redisUtils.get(String.format(ITEM_ID_KEY, credentialType, authDTO.getUserOpenId()));
        if(StringUtils.isEmpty(itemId)){
            itemId = UUID.randomUUID().toString();
            redisUtils.set(String.format(ITEM_ID_KEY, credentialType, authDTO.getUserOpenId()),itemId);
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String serviceStartDate = simpleDateFormat.format(authDTO.getStartTime());
        String serviceEndDate = simpleDateFormat.format(authDTO.getEndTime());
        List<PedestrianAuthHuaWeiIoTDTO.IotDevice> deviceList = new ArrayList<>();
        deviceList.addAll( authDTO.getAddedDeviceOpenIdList().stream()
                .map(deviceOpenId -> PedestrianAuthHuaWeiIoTDTO.IotDevice.builder().deviceGuid(deviceOpenId).isDeleted(0).build())
                .collect(Collectors.toList()));
        //与第三方沟通删除设备时 直接不放设备即可
        /*deviceList.addAll( authDTO.getDeletedDeviceOpenIdList().stream()
                .map(deviceOpenId -> PedestrianAuthHuaWeiIoTDTO.IotDevice.builder().deviceGuid(deviceOpenId).isDeleted(1).build())
                .collect(Collectors.toList()));*/
        String cardNumber = authDTO.getCardNumber();//人脸卡号不能与门禁卡共用一张卡号
        if(credentialType == 170){
            cardNumber = "FF"+cardNumber.substring(2);
        }
        PedestrianAuthHuaWeiIoTDTO authHuaWeiIoTDTO = PedestrianAuthHuaWeiIoTDTO.builder()
                .cardServices(Collections.singletonList(PedestrianAuthHuaWeiIoTDTO.CardService.builder()
                        .deviceList(deviceList)
                        .itemId(itemId)
                        .credentialType(credentialType)
                        .credentialNo(cardNumber)
                        .personId(authDTO.getUserOpenId())
                        .serviceStartDate(serviceStartDate)
                        .serviceEndDate(serviceEndDate)
                        .cardKey("1234")
                        .templateData(faceBase)
                        .isDeleted(0)
                        .startTime1("00:00")
                        .endTime1("23:59")
                        .build()))
                .build();
        Map<String,Object> param = new HashMap<>();
        param.put("value",authHuaWeiIoTDTO);
        JSONObject resultObject = generalHuaWeiIoTDAHandler.command(configDTO.getAk(), configDTO.getSk(), configDTO.getRegion(), configDTO.getUserDeviceId(), HuaWeiIoTDAConstant.SERVICE_AUTHORIZATION, HuaWeiIoTDAConstant.COMMAND_AUTH, param);
        PedestrianAuthHuaWeiIoTDTO huaWeiIoTDTO = resultObject.getJSONObject("paras").getObject("CommandRsBody", PedestrianAuthHuaWeiIoTDTO.class);
        log.info("iotda更新授权返回：{}",huaWeiIoTDTO.toString());
        return null;
    }

    /**
     * 删除授权信息
     *
     * @param authDTO
     * @return
     */
    public String pedestrianAuthDelete(PedestrianIntegrationConfigDTO configDTO, AuthDTO authDTO) {
        Integer credentialType = null;
        String faceBase = null;
        if(!CollectionUtils.isEmpty(authDTO.getCardNumberList())||!StringUtils.isEmpty(authDTO.getCardNumber())){
            credentialType = 1;
        }
        if(!StringUtils.isEmpty(authDTO.getFaceUrl())){
            credentialType = 170;
            faceBase = Base64Utils.imageUrlToBase64(authDTO.getFaceUrl());
        }
        if(credentialType == null){
            return null;
        }
        String cardNumber = authDTO.getCardNumber();//人脸卡号不能与门禁卡共用一张卡号
        if(credentialType == 170){
            cardNumber = "FF"+cardNumber.substring(2);
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String serviceStartDate = simpleDateFormat.format(new Date());
        String serviceEndDate = simpleDateFormat.format(new Date());
        if(authDTO.getStartTime()!=null && authDTO.getEndTime()!=null){
            serviceStartDate = simpleDateFormat.format(authDTO.getStartTime());
            serviceEndDate = simpleDateFormat.format(authDTO.getEndTime());
        }
        String itemId = (String) redisUtils.get(String.format(ITEM_ID_KEY, credentialType, authDTO.getUserOpenId()));
        List<PedestrianAuthHuaWeiIoTDTO.IotDevice> deviceList = new ArrayList<>();
        deviceList.addAll( authDTO.getDeletedDeviceOpenIdList().stream()
                .map(deviceOpenId -> PedestrianAuthHuaWeiIoTDTO.IotDevice.builder().deviceGuid(deviceOpenId).isDeleted(1).build())
                .collect(Collectors.toList()));
        //删除授权信息 第一步先注销凭证
        PedestrianAuthHuaWeiIoTDTO authHuaWeiIoTDTO = PedestrianAuthHuaWeiIoTDTO.builder()
                .cardServices(Collections.singletonList(PedestrianAuthHuaWeiIoTDTO.CardService.builder()
                        .isDeleted(0)
                        .deviceList(deviceList)
                        .credentialNo(cardNumber)
                        .credentialType(credentialType)
                        .itemId(itemId)
                        .week("1111111")
                        .cardKey("1234")
                        .serviceStartDate(serviceStartDate)
                        .serviceEndDate(serviceEndDate)
                        .personId(authDTO.getUserOpenId())
                        .templateData(faceBase)
                        .build()))
                .build();
        Map<String,Object> param = new HashMap<>();
        param.put("value",authHuaWeiIoTDTO);
        JSONObject resultObject = generalHuaWeiIoTDAHandler.command(configDTO.getAk(), configDTO.getSk(), configDTO.getRegion(), configDTO.getUserDeviceId(), HuaWeiIoTDAConstant.SERVICE_AUTHORIZATION, HuaWeiIoTDAConstant.COMMAND_AUTH, param);

        //删除授权信息 第二步注销服务
        PedestrianAuthHuaWeiIoTDTO authHuaWeiIoTServiceDTO = PedestrianAuthHuaWeiIoTDTO.builder()
                .cardServices(Collections.singletonList(PedestrianAuthHuaWeiIoTDTO.CardService.builder()
                        .isDeleted(1)
                        .deviceList(deviceList)
                        .credentialNo(cardNumber)
                        .credentialType(credentialType)
                        .credentialStatus("BACKED")//注销
                        .itemId(itemId)
                        .week("1111111")
                        .cardKey("1234")
                        .serviceStartDate(serviceStartDate)
                        .serviceEndDate(serviceEndDate)
                        .personId(authDTO.getUserOpenId())
                        .templateData(faceBase)
                        .build()))
                .build();
        Map<String,Object> paramService = new HashMap<>();
        paramService.put("value",authHuaWeiIoTServiceDTO);
        JSONObject resultObjectService = generalHuaWeiIoTDAHandler.command(configDTO.getAk(), configDTO.getSk(), configDTO.getRegion(), configDTO.getUserDeviceId(), HuaWeiIoTDAConstant.SERVICE_AUTHORIZATION, HuaWeiIoTDAConstant.COMMAND_AUTH, paramService);
        return null;
    }

    private void handleCardAndFace(){

    }

}
